home *** CD-ROM | disk | FTP | other *** search
/ Total Network Tools 2002 / NextStepPublishing-TotalNetworkTools2002-Win95.iso / Archive / Misc Servers / Zope.exe / RESOURCE.PY < prev    next >
Encoding:
Python Source  |  2000-07-12  |  16.5 KB  |  401 lines

  1. ##############################################################################
  2. # Zope Public License (ZPL) Version 1.0
  3. # -------------------------------------
  4. # Copyright (c) Digital Creations.  All rights reserved.
  5. # This license has been certified as Open Source(tm).
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions are
  8. # met:
  9. # 1. Redistributions in source code must retain the above copyright
  10. #    notice, this list of conditions, and the following disclaimer.
  11. # 2. Redistributions in binary form must reproduce the above copyright
  12. #    notice, this list of conditions, and the following disclaimer in
  13. #    the documentation and/or other materials provided with the
  14. #    distribution.
  15. # 3. Digital Creations requests that attribution be given to Zope
  16. #    in any manner possible. Zope includes a "Powered by Zope"
  17. #    button that is installed by default. While it is not a license
  18. #    violation to remove this button, it is requested that the
  19. #    attribution remain. A significant investment has been put
  20. #    into Zope, and this effort will continue if the Zope community
  21. #    continues to grow. This is one way to assure that growth.
  22. # 4. All advertising materials and documentation mentioning
  23. #    features derived from or use of this software must display
  24. #    the following acknowledgement:
  25. #      "This product includes software developed by Digital Creations
  26. #      for use in the Z Object Publishing Environment
  27. #      (http://www.zope.org/)."
  28. #    In the event that the product being advertised includes an
  29. #    intact Zope distribution (with copyright and license included)
  30. #    then this clause is waived.
  31. # 5. Names associated with Zope or Digital Creations must not be used to
  32. #    endorse or promote products derived from this software without
  33. #    prior written permission from Digital Creations.
  34. # 6. Modified redistributions of any form whatsoever must retain
  35. #    the following acknowledgment:
  36. #      "This product includes software developed by Digital Creations
  37. #      for use in the Z Object Publishing Environment
  38. #      (http://www.zope.org/)."
  39. #    Intact (re-)distributions of any official Zope release do not
  40. #    require an external acknowledgement.
  41. # 7. Modifications are encouraged but must be packaged separately as
  42. #    patches to official Zope releases.  Distributions that do not
  43. #    clearly separate the patches from the original work must be clearly
  44. #    labeled as unofficial distributions.  Modifications which do not
  45. #    carry the name Zope may be packaged in any form, as long as they
  46. #    conform to all of the clauses above.
  47. # Disclaimer
  48. #   THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
  49. #   EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  50. #   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  51. #   PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
  52. #   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  53. #   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  54. #   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  55. #   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  56. #   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  57. #   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  58. #   OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  59. #   SUCH DAMAGE.
  60. # This software consists of contributions made by Digital Creations and
  61. # many individuals on behalf of Digital Creations.  Specific
  62. # attributions are listed in the accompanying credits file.
  63. ##############################################################################
  64.  
  65. """WebDAV support - resource objects."""
  66.  
  67. __version__='$Revision: 1.32.2.1 $'[11:-2]
  68.  
  69. import sys, os, string, mimetypes, davcmds, ExtensionClass
  70. from common import absattr, aq_base, urlfix, rfc1123_date
  71. from urllib import quote, unquote
  72. import Globals, time
  73.  
  74. class Resource(ExtensionClass.Base):
  75.     """The Resource mixin class provides basic WebDAV support for
  76.     non-collection objects. It provides default implementations
  77.     for most supported WebDAV HTTP methods, however certain methods
  78.     such as PUT should be overridden to ensure correct behavior in
  79.     the context of the object type."""
  80.  
  81.     __dav_resource__=1
  82.  
  83.     __http_methods__=('GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'OPTIONS',
  84.                       'TRACE', 'PROPFIND', 'PROPPATCH', 'MKCOL', 'COPY',
  85.                       'MOVE',
  86.                       )
  87.  
  88.     __ac_permissions__=(
  89.         ('View',                             ('HEAD',)),
  90.         ('Access contents information',      ('PROPFIND',)),
  91.         ('Manage properties',                ('PROPPATCH',)),
  92.         ('Delete objects',                   ('DELETE',)),
  93.     )
  94.  
  95.     def dav__init(self, request, response):
  96.         # Init expected HTTP 1.1 / WebDAV headers which are not
  97.         # currently set by the response object automagically.
  98.         # Note we set an borg-specific header for ie5 :(
  99.         response.setHeader('Connection', 'close', 1)
  100.         response.setHeader('Date', rfc1123_date(), 1)
  101.         response.setHeader('MS-Author-Via', 'DAV')
  102.  
  103.     def dav__validate(self, object, methodname, REQUEST):
  104.         msg='<strong>You are not authorized to access this resource.</strong>'
  105.         method=None
  106.         if hasattr(object, methodname):
  107.             method=getattr(object, methodname)
  108.         else:
  109.             try:    method=object.aq_acquire(methodname)
  110.             except: method=None
  111.  
  112.         if method is not None:
  113.             try: return getSecurityManager().validateValue(method)
  114.             except: pass
  115.  
  116.         raise 'Unauthorized', msg
  117.  
  118.  
  119.     # WebDAV class 1 support
  120.  
  121.     def HEAD(self, REQUEST, RESPONSE):
  122.         """Retrieve resource information without a response body."""
  123.         self.dav__init(REQUEST, RESPONSE)
  124.         
  125.         content_type=None
  126.         if hasattr(self, 'content_type'):
  127.             content_type=absattr(self.content_type)
  128.         if content_type is None:
  129.             url=urlfix(REQUEST['URL'], 'HEAD')
  130.             name=unquote(filter(None, string.split(url, '/'))[-1])
  131.             content_type, encoding=mimetypes.guess_type(name)
  132.         if content_type is None:
  133.             if hasattr(self, 'default_content_type'):
  134.                 content_type=absattr(self.default_content_type)
  135.         if content_type is None:
  136.             content_type = 'application/octet-stream'
  137.         RESPONSE.setHeader('Content-Type', string.lower(content_type))
  138.  
  139.         if hasattr(aq_base(self), 'get_size'):
  140.             RESPONSE.setHeader('Content-Length', absattr(self.get_size))
  141.         if hasattr(self, '_p_mtime'):
  142.             mtime=rfc1123_date(self._p_mtime)
  143.             RESPONSE.setHeader('Last-Modified', mtime)
  144.         RESPONSE.setStatus(200)
  145.         return RESPONSE
  146.  
  147.     def PUT(self, REQUEST, RESPONSE):
  148.         """Replace the GET response entity of an existing resource.        
  149.         Because this is often object-dependent, objects which handle
  150.         PUT should override the default PUT implementation with an
  151.         object-specific implementation. By default, PUT requests
  152.         fail with a 405 (Method Not Allowed)."""
  153.         self.dav__init(REQUEST, RESPONSE)
  154.         raise 'Method Not Allowed', 'Method not supported for this resource.'
  155.  
  156.     OPTIONS__roles__=None
  157.     def OPTIONS(self, REQUEST, RESPONSE):
  158.         """Retrieve communication options."""
  159.         self.dav__init(REQUEST, RESPONSE)
  160.         RESPONSE.setHeader('Allow', string.join(self.__http_methods__,', '))
  161.         RESPONSE.setHeader('Content-Length', 0)
  162.         RESPONSE.setHeader('DAV', '1', 1)
  163.         RESPONSE.setStatus(200)
  164.         return RESPONSE
  165.  
  166.     TRACE__roles__=None
  167.     def TRACE(self, REQUEST, RESPONSE):
  168.         """Return the HTTP message received back to the client as the
  169.         entity-body of a 200 (OK) response. This will often usually
  170.         be intercepted by the web server in use. If not, the TRACE
  171.         request will fail with a 405 (Method Not Allowed), since it
  172.         is not often possible to reproduce the HTTP request verbatim
  173.         from within the Zope environment."""
  174.         self.dav__init(REQUEST, RESPONSE)
  175.         raise 'Method Not Allowed', 'Method not supported for this resource.'
  176.  
  177.     def DELETE(self, REQUEST, RESPONSE):
  178.         """Delete a resource. For non-collection resources, DELETE may
  179.         return either 200 or 204 (No Content) to indicate success."""
  180.         self.dav__init(REQUEST, RESPONSE)
  181.         url=urlfix(REQUEST['URL'], 'DELETE')
  182.         name=unquote(filter(None, string.split(url, '/'))[-1])
  183.         # TODO: add lock checking here
  184.         self.aq_parent._delObject(name)
  185.         RESPONSE.setStatus(204)
  186.         return RESPONSE
  187.  
  188.     def PROPFIND(self, REQUEST, RESPONSE):
  189.         """Retrieve properties defined on the resource."""
  190.         self.dav__init(REQUEST, RESPONSE)
  191.         cmd=davcmds.PropFind(REQUEST)
  192.         result=cmd.apply(self)
  193.         RESPONSE.setStatus(207)
  194.         RESPONSE.setHeader('Content-Type', 'text/xml; charset="utf-8"')
  195.         RESPONSE.setBody(result)
  196.         return RESPONSE
  197.  
  198.     def PROPPATCH(self, REQUEST, RESPONSE):
  199.         """Set and/or remove properties defined on the resource."""
  200.         self.dav__init(REQUEST, RESPONSE)
  201.         if not hasattr(aq_base(self), 'propertysheets'):
  202.             raise 'Method Not Allowed', (
  203.                   'Method not supported for this resource.')
  204.         # TODO: add lock checking here
  205.         cmd=davcmds.PropPatch(REQUEST)
  206.         result=cmd.apply(self)
  207.         RESPONSE.setStatus(207)
  208.         RESPONSE.setHeader('Content-Type', 'text/xml; charset="utf-8"')
  209.         RESPONSE.setBody(result)
  210.         return RESPONSE
  211.  
  212.     def MKCOL(self, REQUEST, RESPONSE):
  213.         """Create a new collection resource. If called on an existing 
  214.         resource, MKCOL must fail with 405 (Method Not Allowed)."""
  215.         self.dav__init(REQUEST, RESPONSE)
  216.         raise 'Method Not Allowed', 'The resource already exists.'
  217.  
  218.     def COPY(self, REQUEST, RESPONSE):
  219.         """Create a duplicate of the source resource whose state
  220.         and behavior match that of the source resource as closely
  221.         as possible. Though we may later try to make a copy appear
  222.         seamless across namespaces (e.g. from Zope to Apache), COPY 
  223.         is currently only supported within the Zope namespace."""
  224.         self.dav__init(REQUEST, RESPONSE)
  225.         if not hasattr(aq_base(self), 'cb_isCopyable') or \
  226.            not self.cb_isCopyable():
  227.             raise 'Method Not Allowed', 'This object may not be copied.'
  228.         depth=REQUEST.get_header('Depth', 'infinity')
  229.         if not depth in ('0', 'infinity'):
  230.             raise 'Bad Request', 'Invalid Depth header.'
  231.         dest=REQUEST.get_header('Destination', '')
  232.         while dest and dest[-1]=='/':
  233.             dest=dest[:-1]
  234.         if not dest:
  235.             raise 'Bad Request', 'Invalid Destination header.'
  236.         oflag=string.upper(REQUEST.get_header('Overwrite', 'F'))
  237.         if not oflag in ('T', 'F'):
  238.             raise 'Bad Request', 'Invalid Overwrite header.'
  239.         path, name=os.path.split(dest)
  240.         name=unquote(name)
  241.         try: parent=REQUEST.resolve_url(path)
  242.         except ValueError:
  243.             raise 'Conflict', 'Attempt to copy to an unknown namespace.'
  244.         except 'Not Found':
  245.             raise 'Conflict', 'Object ancestors must already exist.'
  246.         except:
  247.             t, v, tb=sys.exc_info()
  248.             raise t, v
  249.         if hasattr(parent, '__null_resource__'):
  250.             raise 'Conflict', 'Object ancestors must already exist.'
  251.         existing=hasattr(aq_base(parent), name)
  252.         if existing and oflag=='F':
  253.             raise 'Precondition Failed', 'Destination resource exists.'
  254.         try: parent._checkId(name, allow_dup=1)
  255.         except: raise 'Forbidden', sys.exc_info()[1]
  256.         try: parent._verifyObjectPaste(self)
  257.         except 'Unauthorized':
  258.             raise 'Unauthorized', sys.exc_info()[1]
  259.         except: raise 'Forbidden', sys.exc_info()[1]
  260.  
  261.         ob=self._getCopy(parent)
  262.         ob.manage_afterClone(ob)
  263.         ob._setId(name)
  264.         if depth=='0' and hasattr(ob, '__dav_collection__'):
  265.             for id in ob.objectIds():
  266.                 ob._delObject(id)
  267.         if existing:
  268.             object=getattr(parent, name)
  269.             self.dav__validate(object, 'DELETE', REQUEST)
  270.             parent._delObject(name)
  271.         parent._setObject(name, ob)
  272.         #ob=ob.__of__(parent)
  273.         #ob._postCopy(parent, op=0)
  274.         RESPONSE.setStatus(existing and 204 or 201)
  275.         if not existing:
  276.             RESPONSE.setHeader('Location', dest)
  277.         RESPONSE.setBody('')
  278.         return RESPONSE
  279.  
  280.     def MOVE(self, REQUEST, RESPONSE):
  281.         """Move a resource to a new location. Though we may later try to
  282.         make a move appear seamless across namespaces (e.g. from Zope
  283.         to Apache), MOVE is currently only supported within the Zope
  284.         namespace."""
  285.         self.dav__init(REQUEST, RESPONSE)
  286.         self.dav__validate(self, 'DELETE', REQUEST)
  287.         if not hasattr(aq_base(self), 'cb_isMoveable') or \
  288.            not self.cb_isMoveable():
  289.             raise 'Method Not Allowed', 'This object may not be moved.'
  290.         dest=REQUEST.get_header('Destination', '')
  291.         while dest and dest[-1]=='/':
  292.             dest=dest[:-1]
  293.         if not dest:
  294.             raise 'Bad Request', 'No destination given'
  295.         flag=REQUEST.get_header('Overwrite', 'F')
  296.         flag=string.upper(flag)
  297.         body=REQUEST.get('BODY', '')
  298.         path, name=os.path.split(dest)
  299.         name=unquote(name)
  300.         try: parent=REQUEST.resolve_url(path)
  301.         except ValueError:
  302.             raise 'Conflict', 'Attempt to move to an unknown namespace.'
  303.         except 'Not Found':
  304.             raise 'Conflict', 'The resource %s must exist.' % path
  305.         except:
  306.             t, v, tb=sys.exc_info()
  307.             raise t, v
  308.         if hasattr(parent, '__null_resource__'):
  309.             raise 'Conflict', 'The resource %s must exist.' % path
  310.         existing=hasattr(aq_base(parent), name)
  311.         if existing and flag=='F':
  312.             raise 'Precondition Failed', 'Resource %s exists.' % dest
  313.         try: parent._checkId(name, allow_dup=1)
  314.         except: raise 'Forbidden', sys.exc_info()[1]
  315.         try: parent._verifyObjectPaste(self)
  316.         except: raise 'Forbidden', sys.exc_info()[1]
  317.  
  318.         ob=aq_base(self._getCopy(parent))
  319.         self.aq_parent._delObject(absattr(self.id))
  320.         ob._setId(name)
  321.         if existing:
  322.             object=getattr(parent, name)
  323.             self.dav__validate(object, 'DELETE', REQUEST)
  324.             parent._delObject(name)            
  325.         parent._setObject(name, ob)
  326.         #ob=ob.__of__(parent)
  327.         #ob._postCopy(parent, op=1)
  328.         RESPONSE.setStatus(existing and 204 or 201)
  329.         if not existing:
  330.             RESPONSE.setHeader('Location', dest)
  331.         RESPONSE.setBody('')
  332.         return RESPONSE
  333.  
  334.  
  335.     # WebDAV Class 2  is currently not really supported - the
  336.     # following merely fakes enough class 2 support to allow
  337.     # operation with MS O2K.
  338.  
  339.     _v_dav_lock=None
  340.  
  341.     def dav__genlocktoken(self):
  342.         return 'AA9F6414-1D77-11D3-B825-00105A989226:%.03f' % time.time()
  343.  
  344.     def LOCK(self, REQUEST, RESPONSE):
  345.         """Lock a resource"""
  346.         self.dav__init(REQUEST, RESPONSE)
  347.         token=self.dav__genlocktoken()
  348.         self._v_dav_lock=token
  349.         RESPONSE.setStatus(200)
  350.         RESPONSE.setHeader('Content-Type', 'text/xml; charset="utf-8"')
  351.         RESPONSE.setHeader('Lock-Token', '<locktoken:%s>' % token)
  352.         RESPONSE.setBody(self.fake_lock_xml % token)
  353.         return RESPONSE
  354.  
  355.     def UNLOCK(self, REQUEST, RESPONSE):
  356.         """Remove an existing lock on a resource."""
  357.         self.dav__init(REQUEST, RESPONSE)
  358.         self._v_dav_lock=None
  359.         RESPONSE.setStatus(204)
  360.         return RESPONSE
  361.  
  362.     fake_lock_xml="""<?xml version="1.0" encoding="utf-8" ?>
  363. <d:prop xmlns:d="DAV:">
  364.   <d:lockdiscovery>
  365.     <d:activelock>
  366.       <d:locktype><d:write/></d:locktype>
  367.       <d:lockscope><d:exclusive/></d:lockscope>
  368.       <d:depth>0</d:depth>
  369.       <d:owner>you</d:owner>
  370.       <d:timeout>Second-120</d:timeout>
  371.       <d:locktoken>
  372.         <d:href>locktoken:%s</d:href>
  373.       </d:locktoken>
  374.     </d:activelock>
  375.   </d:lockdiscovery>
  376. </d:prop>"""
  377.  
  378.  
  379. Globals.default__class_init__(Resource)
  380.